package com.example.yiparkapplication;

import androidx.annotation.NonNull;

import android.app.AlertDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Looper;
import android.util.Log;
import android.view.View;
import android.widget.Button;

import com.example.yiparkapplication.activity.IndexActivity;
import com.example.yiparkapplication.activity.index.activity.ConvenientPaymentActivity.CarOrderActivity;
import com.example.yiparkapplication.util.BaseActivity;
import com.rey.material.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSONObject;
import com.example.yiparkapplication.activity.RegisterActivity;
import com.example.yiparkapplication.constant.API;
import com.example.yiparkapplication.constant.Constant;
import com.example.yiparkapplication.util.Common;
import com.example.yiparkapplication.util.MD5Utils;
import com.example.yiparkapplication.util.ProgressDialogUtil;
import com.example.yiparkapplication.activity.ResetPasswordActivity;


import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class MainActivity extends BaseActivity {

    private AlertDialog progressDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        automaticLogin();
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login_layout);
        Button loginButton = (Button) findViewById(R.id.id_login);
        loginButton.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v){
                EditText ephone = (EditText) findViewById(R.id.id_login_phone);
                String phoneNumber = ephone.getText().toString().trim();
                EditText epassword = (EditText) findViewById(R.id.id_login_password);
                String password = epassword.getText().toString().trim();
//                checkInfo(phoneNumber, password);
                Intent intent = new Intent(MainActivity.this, IndexActivity.class);
                startActivity(intent);
            }
        });
        TextView registerTextView = (TextView)findViewById(R.id.id_user_register);
        registerTextView.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v){
                Intent intent = new Intent(MainActivity.this, RegisterActivity.class);
                startActivity(intent);
            }
        });
        TextView resetPasswordTextView = (TextView)findViewById(R.id.id_forget_password);
        resetPasswordTextView.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v){
                Intent intent = new Intent(MainActivity.this, ResetPasswordActivity.class);
                startActivity(intent);
            }
        });
    }

    private void automaticLogin(){
        SharedPreferences pref = getSharedPreferences("data", MODE_PRIVATE);
        String ifLogin = pref.getString("ifLogin", "");
        if ("true".equals(ifLogin)){
            String phoneNumber = pref.getString("phoneNumber", "");
            String password = pref.getString("password", "");
            checkInfo(phoneNumber, password);
        }
    }

    /**
     * 检查信息登录
     * 用户手机号
     * 用户密码*/
    private void checkInfo(final String phoneNumber, final String password){
        if (phoneNumber == null || "".equals(phoneNumber)){
            Toast.makeText(this, Constant.ON_PHONE, Toast.LENGTH_LONG).show();
            return;
        }
        if (password == null || "".equals(password)){
            Toast.makeText(this, Constant.ON_PASSWORD, Toast.LENGTH_LONG).show();
            return;
        }
        Log.d("inputinfo", "checkInfo: " + phoneNumber);
        Log.d("inputinfo", "checkInfo: " + password);
        progressDialog = ProgressDialogUtil.returnProgressDialog(MainActivity.this);
        progressDialog.show();
        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder()
                .url(API.HOST + API.URL_GET_USER_DATA + "?phoneNumber=" + phoneNumber + "&password=" + MD5Utils.md5Password(password))
                .build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e){
                progressDialog.dismiss();
                Common.failureMessage(e.getMessage(), getApplicationContext());
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response)throws IOException{
                progressDialog.dismiss();
                String tempResponse = response.body().string();
                JSONObject joOut = Common.tempResponseException(tempResponse, getApplicationContext());
                Log.d("check login info joout", joOut.toString());
                int code = joOut.getIntValue("code");
                if (code == 100){
                    Intent intent = new Intent(MainActivity.this, IndexActivity.class);
                    startActivity(intent);
                    String userId = joOut.getJSONObject("object").getString("parkUserId");
                    String phone = joOut.getJSONObject("object").getString("parkUserAccount");
                    String licensePlate = joOut.getJSONObject("object").getString("parkUserLicensePlate");
                    String userName = joOut.getJSONObject("object").getString("parkUserName");
                    SharedPreferences.Editor editor = getSharedPreferences("data",MODE_PRIVATE).edit();
                    editor.putString("phoneNumber", phoneNumber);
                    editor.putString("password", password);
                    editor.putString("userId", userId);
                    editor.putString("licensePlate", licensePlate);
                    editor.putString("userName", userName);
                    editor.putString("ifLogin", Constant.LOGIN);
                    editor.apply();
                    CarOrderActivity.getUserId(userId, phone);
//                    AddCarDetailsActivity.getUserId(userId);
                }else{
                    Looper.prepare();
                    Toast.makeText(getApplicationContext(), joOut.getString("msg"), Toast.LENGTH_LONG).show();
                    Looper.loop();
                }
            }
        });
    }

}